<template>
  <div>
    <el-dialog
      title="设置命令映射"
      :visible.sync="commandMapInfo.show"
      :close-on-click-modal="false"
      width="800px"
      top="10vh"
      append-to-body
      center>
      <el-form :ref="commandMapFormRef" :model="commandMapForm" :rules="commandMapFormRules" size="small"
               label-width="120px">
        <div v-if="commandMapInfo.type === 'Func'">
          <el-form-item label="参数生成函数">
            <el-select v-model="commandMapForm.analyzeFunc" clearable filterable class="width-100"
                       placeholder="请选择参数生成函数">
              <el-option label="无" value=""></el-option>
              <el-option :label="func.label" :value="func.value" :key="idx"
                         v-for="(func, idx) in analyzeFuncData"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="选择参数名" v-if="!isEditor">
            <el-radio-group v-model="generalParamRadio">
              <el-radio :label="0">关联</el-radio>
              <el-radio :label="1">新增</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="参数名" prop="paramName" v-if="generalParamRadio === 0 || isEditor">
            <el-select v-model="commandMapForm.paramName" clearable filterable class="width-100"
                       placeholder="请选择参数名"
                       @change="paramNameChanged">
              <el-option :label="map.paramKey" :value="map.paramKey" :key="idx"
                         v-for="(map, idx) in paramNameSelData">
                <span>{{map.paramKey}}</span>
                <span class="mar-lft font-color-warning">{{map.paramAlias || ''}}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <div  v-if="generalParamRadio===1">
            <el-form-item label="参数名" prop="paramName">
              <el-input v-model="commandMapForm.paramName" placeholder="请输入命令方法名"></el-input>
            </el-form-item>
            <el-form-item label="参数别名" prop="paramAlias">
              <el-input v-model="commandMapForm.paramAlias" placeholder="请输入命令方法名"></el-input>
            </el-form-item>
            <el-form-item label="参数存储键">
              <el-select v-model="commandMapForm.storeKey" @change="storeKeyChanged"  allow-create
                         clearable filterable class="width-100" placeholder="请选择参数存储键">
                <el-option-group
                  v-for="(group, idx) in storeKeyData"
                  :key="idx"
                  :label="group.label">
                  <el-option
                    v-for="(item, idx) in group.options"
                    :key="idx"
                    :label="item.name"
                    :value="item.name">
                    <span>{{item.name}}</span>
                    <span class="mar-lft font-color-warning">{{item.alias || ''}}</span>
                  </el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
            <el-form-item label="参数存储键别名" prop="storeKeyAlias" >
              <el-input v-model="commandMapForm.storeKeyAlias" placeholder="请输入命令方法名"></el-input>
            </el-form-item>
            </div>
          <el-form-item label="上报类型" prop="reportType">
            <el-radio-group v-model="commandMapForm.reportType">
              <el-radio :label="param.value" :key="idx" v-for="(param, idx) in commonConfig.reportType">
                {{param.label}}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="映射方式" prop="mapWay">
            <el-radio-group v-model="commandMapForm.mapWay">
              <el-radio :label="way.value" :key="idx" v-for="(way, idx) in commonConfig.commandMapWay">
                {{way.label}}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="数据类型" prop="dataType">
            <el-radio-group v-model="commandMapForm.dataType">
              <el-radio :label="type.value" :key="idx"
                        v-for="(type, idx) in commonConfig.dataType">{{type.label}}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="数据长度(byte)">
            <el-input-number class="width-50" v-model="commandMapForm.dataLen" :min="1"></el-input-number>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item v-if="commandMapForm.commandType !== 5" label="参数单位">
                <el-select v-model="commandMapForm.unit" clearable filterable class="width-100"
                           placeholder="请选择参数单位">
                  <el-option :label="unit.label" :value="unit.value" :key="idx"
                             v-for="(unit, idx) in commonConfig.paramUnit"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据精度">
                <el-input-number class="width-100" v-model="commandMapForm.scale" :min="1"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="字节解析顺序">
            <el-radio-group v-model="commandMapForm.byteOrder">
              <el-radio :label="order.value" :key="idx" v-for="(order, idx) in commonConfig.byteOrder">
                {{order.label}}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="commandMapForm.mapWay === commonConfig.commandMapWay[1].value" label="参数可选值">
            <EnumDynamic
              :isEditor="isEditor"
              v-if="commandMapInfo.type === 'Req'"
              :is-key-selector="true"
              :dynamic-sel-data="enumSelData"
              :dynamic-data="enumList"
              :data-type="commandMapForm.dataType"
              third-key="minCtrInterval"
            ></EnumDynamic>
            <EnumDynamic
              :isEditor="isEditor"
              v-if="commandMapInfo.type === 'Rsp'"
              :is-value-selector="true"
              :dynamic-sel-data="enumSelData"
              :dynamic-data="enumList"
              :data-type="commandMapForm.dataType"
            ></EnumDynamic>
          </el-form-item>
          <el-form-item v-if="commandMapForm.mapWay === commonConfig.commandMapWay[2].value" label="参数取值范围">
            <el-row>
              <el-col :span="11">
                <el-col :span="12" class="pad-rgt-5">
                  <el-input-number class="width-100" size="small"
                                   v-model="fieldMap.preMin">
                  </el-input-number>
                </el-col>
                <el-col :span="12" class="pad-rgt-5">
                  <el-input-number class="width-100" size="small"
                                   v-model="fieldMap.preMax">
                  </el-input-number>
                </el-col>
              </el-col>
              <el-col :span="2" class="text-align-center pad-rgt-5">=></el-col>
              <el-col :span="11">
                <el-col :span="12" class="pad-rgt-5">
                  <el-input-number class="width-100" size="small"
                                   v-model="fieldMap.postMin">
                  </el-input-number>
                </el-col>
                <el-col :span="12">
                  <el-input-number class="width-100" size="small"
                                   v-model="fieldMap.postMax">
                  </el-input-number>
                </el-col>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item v-if="commandMapForm.mapWay === commonConfig.commandMapWay[3].value" label="映射方法">
            <el-select v-model="commandMapForm.customMapFunc" clearable filterable class="width-100"
                       placeholder="请选择映射方法">
              <el-option label="无" value=""></el-option>
              <el-option :label="func.label" :value="func.value" :key="idx"
                         v-for="(func, idx) in analyzeFuncData"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="默认值">
            <el-input v-model="commandMapForm.defaultValue" placeholder="请填写默认值"></el-input>
          </el-form-item>
        </div>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="commandMapForm.remarks" placeholder="请填写备注"></el-input>
        </el-form-item>
        <div class="text-align-right">
          <el-form-item>
            <el-button @click="commandMapFormCanceled">取消</el-button>
            <el-button type="primary" @click="commandMapFormSubmitted">保存</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import {commonConfig} from "@/config/common";
  import {deepCopyWithJson} from "@/utils";
  import EnumDynamic from "../../../../components/EnumDynamic";

  const initFieldMap = {
    preMin: 0,
    preMax: 100,
    postMin: 0,
    postMax: 100,
  };

  export default {
    name: "DeviceCommandMap",
    components: {
      EnumDynamic
    },
    props: {
      commandMapInfo: {
        default: () => {
          return {
            show: false,
            type: 'Req',
            tag: {},
            genCommInfo: {}
          }
        }
      },
      isEditor: {
        type: Boolean,
        default: false
      },
      storeKeyData: {
        type: Array,
        default:[]
      }
    },
    data() {
      return {
        commonConfig: commonConfig,
        commandMapForm: {},
        commandMapFormRules: {
          paramName: [
            {required: true, message: '请选择参数名', trigger: 'blur'}
          ],
          reportType: [
            {required: true, message: '请选择上报类型', trigger: 'blur'}
          ],
          mapWay: [
            {required: true, message: '请选择映射方式', trigger: 'blur'}
          ],
          dataType: [
            {required: true, message: '请选择数据类型', trigger: 'blur'}
          ],
        },
        commandMapFormRef: 'commandMapFormRef',
        enumList: [],
        fieldMap: {},
        enumSelData: [], // 参数可选值从通用命令中包含的枚举中选择
        analyzeFuncData: [],
        generalParamRadio:0,
      }
    },
    computed: {
      paramNameSelData() {
        const {statusParams = [], controlParams = []} = this.commandMapInfo.genCommInfo || {};
        switch (this.commandMapInfo.type) {
          case 'Req':
            return controlParams;
          case 'Rsp':
            return statusParams;
          default:
            return [];
        }
      },
    },
    watch: {
      commandMapInfo() {
        this.initCommandMapForm();
        const {commandMap = {}} = this.commandMapInfo.tag;
        this.commandMapForm = {...this.commandMapForm, ...commandMap};
        this.enumList = commandMap.enumList || [];
        this.fieldMap = commandMap.field || initFieldMap;
        // 编辑命令，需要设默认值
        this.paramNameChanged(this.commandMapForm.paramName);
      }
    },
    created() {
      this.getAnalyzeFuncData();
    },
    methods: {
      initCommandMapForm() {
        this.commandMapForm = {
          paramName: '',
          paramType: this.commandMapInfo.type,
          reportType: 2,
          mapWay: 1,
          customMapFunc: '',
          dataType: commonConfig.dataType[0].value,
          unit: '',
          dataLen: '',
          scale: '',
          byteOrder: 1,
          analyzeFunc: '',
          defaultValue: '',
          remarks: '',
        };
        this.enumList = [];
        this.fieldMap = initFieldMap;
      },
      getAnalyzeFuncData() {
        API.analyzeFunc.analyzeFuncAll().then(result => {
          const {data = []} = result;
          this.analyzeFuncData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },
      resetCommandMapForm() {
        const commandMapForm = this.$refs[this.commandMapFormRef];
        commandMapForm && commandMapForm.resetFields();
      },
      // commandMap的paramName更改后，enumSelData需要从选择的参数的枚举中选择
      paramNameChanged(val = '') {
        if (!val) return;
        const {enumList = []} = this.paramNameSelData.find(pn => {
          return pn.paramKey === val
        }) || {};
        this.enumSelData = enumList.map(e => {
          return {
            label: e.key,
            value: e.key,
          }
        });
      },
      commandMapFormCanceled() {
        this.commandMapInfo.show = false;
      },
      commandMapFormSubmitted() {
        this.$refs[this.commandMapFormRef].validate((valid) => {
          if (!valid && this.commandMapInfo.type !== 'Func') return;
          let validCommandMapForm = {};
          switch (this.commandMapForm.mapWay) {
            case 1:
              validCommandMapForm = {enumList: this.enumList};
              break;
            case 2:
              validCommandMapForm = {field: this.fieldMap};
              break;
          }
          this.commandMapInfo.tag['commandMap'] = deepCopyWithJson({
            ...this.commandMapForm,
            ...validCommandMapForm,
            // enumList: this.enumList,
            // field: this.fieldMap
          });
          this.commandMapInfo.show = false;
          this.resetCommandMapForm();
        });
      },
      storeKeyChanged() {
        let destStoreKey = {};
        for (let i = 0; i < this.storeKeyData.length; i++) {
          const sk = this.storeKeyData[i];
          const {options = []} = sk;
          const storeKey = options.find(sk => {
            return sk.name === this.commandMapForm.storeKey
          });
          console.log(111,storeKey)
          if (storeKey) {
            destStoreKey = storeKey;
            break;
          }
        }
        this.$set(this.commandMapForm, 'storeKeyAlias', destStoreKey.alias);
      },
    },
  }
</script>

<style scoped>

</style>
